package com.bdqn.springbootno1.intercept;

import com.bdqn.springbootno1.sys.SessionUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;


//拦截器类
public class TokenIntercept implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        String token = request.getHeader("token");
        if(token==null){
            response.setStatus(401);
        }else if(SessionUtils.get(token)==null){
            response.setStatus(403);    //token传了，但是传得报错了
        }else {
            //效验过期
            String[] split = token.split("-");     //截取token中的存取时间
            String createTime = split[4];
            if(System.currentTimeMillis()-Long.valueOf(createTime)>2*3600*1000){
                response.setStatus(403);
                SessionUtils.remove(token);
            }
            if(requestURI.equals("/appInfo/auditApps")){
                if(split[3].equals("dev")){
                    response.setStatus(401);
                    return false;
                }
            }
            return true;
        }
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
